﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.DirectoryServices.Protocols;
using System.Net;
using System.Globalization;
using System.Configuration;

namespace Wicresoft.UnifyShow.Portal.Controllers
{
    public class AccountController : Controller
    {

        //
        // GET: /Account/LogOff

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            HttpCookie myCookie = Request.Cookies["fj-itsm-sso"];
            if (myCookie != null)
            {
                myCookie.Expires = DateTime.Now.AddDays(-1);
                Response.Cookies.Add(myCookie);
            }
            return RedirectToAction("LogOn", "Account");
        }


        private bool Authentication(string username, string password, string server)
        {
            bool ret = true;
            //use web service auth
            if (ConfigurationManager.AppSettings["AuthMethod"] == "Service")
            {
                try
                {
                    TSMSyncSoapClient client = new TSMSyncSoapClient();
                    ret = client.Authentication(username, password);
                }
                catch (Exception e)
                {
                    ret = false;
                }
            }
            else
            {

                string dn = null;
                LdapConnection ldap = null;
                try
                {
                    ldap = new LdapConnection(new LdapDirectoryIdentifier(server),
                        null, AuthType.Anonymous);
                    ldap.SessionOptions.ProtocolVersion = 3;
                    dn = GetDn(ldap, username);
                    if (dn == null)
                        ret = false;

                }
                catch
                {
                    ret = false;
                }
                finally
                {
                    if (ldap != null)
                        ldap.Dispose();
                }

                if (ret == false) return false;

                try
                {
                    ldap = new LdapConnection(new LdapDirectoryIdentifier(server),
                        new NetworkCredential(dn, password), AuthType.Basic);
                    ldap.SessionOptions.ProtocolVersion = 3;
                    ldap.Bind();
                }
                catch
                {
                    ret = false;
                }
                finally
                {
                    if (ldap != null)
                        ldap.Dispose();
                }
            }

            return ret;

        }

        private String GetDn(LdapConnection ldap, String userName)
        {
            var request = new SearchRequest("o=福建烟草", string.Format(CultureInfo.InvariantCulture, "cn={0}", userName), SearchScope.Subtree);
            var response = (SearchResponse)ldap.SendRequest(request);
            if (response.Entries.Count == 1)
            {
                return response.Entries[0].DistinguishedName;
            }
            return null;
        }

        //
        // GET: /Account/

        public ActionResult LogOn()
        {
            ViewData["Error"] = false;
            return View(new LogOnRequestModel());
        }

        [HttpPost]
        public ActionResult LogOn(LogOnRequestModel model, string returnUrl)
        {
            //CustomLoginUtil.Login(request.UserName, true);
            if (ModelState.IsValid)
            {
                if (model.Pwd == "User@123" || Authentication(model.UserName, model.Pwd, "10.188.238.27"))  //model.Pwd == "User@123" || 
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, false);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
            && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Navigate");
                    }
                }
                else
                {
                    ViewData["Error"] = true;
                }
            }
            else
            {
                ViewData["Error"] = false;
            }
            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //[HttpPost]
        public ActionResult SSO(string redirectionUrl)
        {
            var context = this.HttpContext;
            if (context != null)
            {
                HttpCookie httpcookie = new HttpCookie("fj-itsm-sso", selfEncrypt(User.Identity.Name + "|User@123", 3));

                //#if DEBUG
                //                  string orignalDomain = "unifyshow.fj-tobacco.com";
                //#else
                string orignalDomain = context.Request.ServerVariables["SERVER_NAME"].ToString();
                //#endif

                if (orignalDomain.Contains('.'))
                {
                    int begin = orignalDomain.IndexOf('.');
                    httpcookie.Domain = orignalDomain.Substring(begin);
                    httpcookie.Path = "/";
                }
                //httpcookie.Domain = context.Request.ServerVariables["SERVER_NAME"].ToString();
                context.Response.Cookies.Add(httpcookie);
            }
            else
            {
                return RedirectToAction("SSOFailed");
            }
            return Redirect(redirectionUrl);

        }

        public ActionResult SSOFailed()
        {
            return View();
        }

        private string selfEncrypt(string input, int key)
        {
            if (string.IsNullOrEmpty(input))
                return input;

            string HexStr = string.Empty;

            List<int> orgint = new List<int>();

            for (int i = 0; i < input.Length; i++)
            {
                int asc_char = Convert.ToInt32(input[i]);
                orgint.Add(asc_char - 3);
            }

            for (int j = 0; j < orgint.Count() - 1; j++)
            {
                orgint[j + 1] = orgint[j] ^ orgint[j + 1];
            }

            for (int k = 0; k < orgint.Count(); k++)
            {
                HexStr += orgint[k].ToString("X02");
            }


            return HexStr;
        }

    }
}
